package com.captain.special.链表;


import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Des:
 *
 * @author XL
 * @Date 2022/3/24 9:40
 */
public class 复制带随机指针的链表138 {

    public static void main(String[] args) {
        new 复制带随机指针的链表138().copyRandomList(Node.gentInstance());
    }

    public Node copyRandomList(Node head) {
        if (head == null) {
            return null;
        }
        Node cur = head;
        HashMap<Node, Node> map = new HashMap<>();
        while (cur != null) {
            Node newNode = new Node(cur.val);
            newNode.random = cur.random;
            map.put(cur, newNode);
            cur = cur.next;
        }

        Node dummy = new Node(-1);
        //操作链表
        Node pre = dummy;
        cur = head;
        while (cur != null) {
            //新的node
            Node node = map.get(cur);
            node.random = map.get(node.random);
            pre.next = node;
            pre = pre.next;
            cur = cur.next;
        }
        return dummy.next;
    }
}
